<template>
	<el-dialog :title="!dataForm.userId ? '新增广告' : '修改广告'" :close-on-click-modal="false" :close-on-press-escape="false"
	 :show-close="false" :visible.sync="visible" :fullscreen="true">
		<el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
			<el-row :gutter="20">
				<el-col :span="12">
					<el-form-item label="名称" prop="name">
						<el-input v-model="dataForm.name" placeholder="请输入名称" maxlength="20" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="广告位" prop="adPositionId">
						<el-select clearable v-model="dataForm.adPositionId" placeholder="请选择广告位" style="width: 100%;">
							<el-option v-for="item in adPositionList" :key="item.id" :label="`${item.name}:${item.width}*${item.height}`"
							 :value="item.id">
								<span>{{item.name}}:{{item.width}}*{{item.height}}</span>
							</el-option>
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row :gutter="20">
				<el-col :span="12">
					<el-form-item label="内容" prop="content">
						<el-input v-model="dataForm.content" placeholder="请输入内容" maxlength="30" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="链接" prop="link">
						<el-input v-model="dataForm.link" placeholder="请输入链接" maxlength="30" clearable></el-input>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row :gutter="20">
				<el-col :span="12">
					<el-form-item label="排序" prop="sortOrder">
						<el-input-number v-model="dataForm.sortOrder" controls-position="right" :min="0" label="排序" type="number"></el-input-number>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="结束时间" prop="endTime">
						<el-date-picker v-model="dataForm.endTime" type="datetime" placeholder="选择日期时间">
						</el-date-picker>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row :gutter="20">
				<el-col :span="12">
					<el-form-item label="状态" prop="enabled">
						<el-radio-group v-model="dataForm.enabled">
							<el-radio :label="1">正常</el-radio>
							<el-radio :label="0">禁用</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="媒体类型" prop="mediaType">
						<el-radio-group v-model="dataForm.mediaType">
							<el-radio :label="1" disabled>图片</el-radio>
							<el-radio :label="2" disabled>视频</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row :gutter="20">
				<el-col :span="12">
					<el-form-item label="媒体资源" prop="imageUrl" class="z-media">
						<el-input v-model="dataForm.imageUrl" placeholder="可以输入已知的网络资源/也可以选择上传" maxlength="500" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="" prop="imageUrl">
						<el-upload class="avatar-uploader" :action="updateUrl" :show-file-list="false" :on-success="handleMediaSuccess"
						 :before-upload="beforeMediaUpload">
							<div v-if="dataForm.imageUrl" class="upload-image-cover" @click.stop="handleView()">
								<img :src="previewPic" class="pic-url" />
								<div class="upload-list-cover">
									<i class="el-icon-view" @click.stop="handleView(dataForm.imageUrl)"></i>
									<i class="el-icon-delete" @click.stop="deleteBtn('imageUrl')"></i>
								</div>
							</div>
							<i v-else class="el-icon-plus avatar-uploader-icon"></i>
						</el-upload>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<span slot="footer" class="dialog-footer">
			<el-button @click="cancel()">取消</el-button>
			<el-button type="primary" @click="dataFormSubmit()">确定</el-button>
		</span>
		<!-- 视频预览 -->
		<z-video v-if="zvideoVisible" :url="preVideoUrl" @closeDialog="zvideoVisible=false"></z-video>
	</el-dialog>
</template>

<script>
	import PhotoViewer from 'photoviewer';
	import { getFrameImg } from '@/utils'
	import ZVideo from '@/components/z-video'
	export default {
		data() {
			return {
				visible: false,
				dataForm: {
					id: 0,
					name: "",
					adPositionId: null,
					content: "",
					link: "",
					enabled: 1,
					sortOrder: 1,
					endTime: '',
					mediaType: 1,
					imageUrl: "",
				},
				dataRule: {
					name: [{
						required: true,
						message: '名称不能为空',
						trigger: 'blur'
					}],
					adPositionId: [{
						required: true,
						message: '广告位不能为空',
						trigger: 'blur'
					}],
					imageUrl: [{
						required: true,
						message: '媒体资源不能为空',
						trigger: 'blur'
					}]
				},
				adPositionList: [],
				//图片上传路径
				updateUrl: '',
				//旧图片
				oldImg: [],
				//新图片
				newImg: [],
				previewPic: '',
				zvideoVisible: false,
				preVideoUrl: ''
			}
		},
		components: {
			ZVideo
		},
		created: function() {
			this.updateUrl = this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`)
		},
		methods: {
			init(id) {
				this.dataForm.id = id || 0
				this.visible = true
				this.getAdPositionList()
				if (this.dataForm.id) {
					this.$http({
						url: this.$http.adornUrl(`/back/ad/info/${this.dataForm.id}`),
						method: 'get',
						params: this.$http.adornParams()
					}).then(({
						data
					}) => {
						if (data && data.code === 0) {
							this.dataForm.adPositionId = data.data.adPositionId
							this.dataForm.content = data.data.content
							this.dataForm.enabled = data.data.enabled
							this.dataForm.endTime = data.data.endTime
							this.dataForm.id = data.data.id
							this.dataForm.imageUrl = data.data.imageUrl
							this.dataForm.link = data.data.link
							this.dataForm.mediaType = data.data.mediaType
							this.dataForm.name = data.data.name
							this.dataForm.sortOrder = data.data.sortOrder
							getFrameImg({url:this.dataForm.imageUrl}).then((ret)=>{
								this.previewPic = ret
							})
						}
					})
				}
			},
			// 表单提交
			dataFormSubmit() {
				this.$refs['dataForm'].validate((valid) => {
					if (valid) {
						this.$http({
							url: this.$http.adornUrl(`/back/ad/${!this.dataForm.id ? 'save' : 'update'}`),
							method: 'post',
							data: this.$http.adornData({
								'id': this.dataForm.id || undefined,
								'name': this.dataForm.name,
								'adPositionId': this.dataForm.adPositionId,
								'content': this.dataForm.content,
								'link': this.dataForm.link,
								'enabled': this.dataForm.enabled,
								'sortOrder': this.dataForm.sortOrder,
								'endTime': this.dataForm.endTime,
								'mediaType': this.dataForm.mediaType,
								'imageUrl': this.dataForm.imageUrl,
							})
						}).then(({
							data
						}) => {
							if (data && data.code === 0) {
								this.deletePics(this.oldImg)
								this.$message({
									message: '操作成功',
									type: 'success',
									duration: 1500,
									onClose: () => {
										this.visible = false
										this.$emit('refreshDataList')
									}
								})
							} else {
								this.$message.error(data.msg)
							}
						})
					}
				})
			},
			// 获取广告位置列表
			getAdPositionList() {
				this.$http({
					url: this.$http.adornUrl(`/back/adPosition/queryAll`),
					method: 'get',
					params: this.$http.adornParams()
				}).then(({
					data
				}) => {
					if (data && data.code === 0) {
						this.adPositionList = data.data
					} else {
						this.adPositionList = []
					}
				})
			},
			//媒体资源上传成功时的钩子
			handleMediaSuccess(response) {
				if (response && response.code === 0) {
					this.dataForm.imageUrl = response.url
					this.newImg.push(response.url)
					getFrameImg({url:this.dataForm.imageUrl}).then((ret)=>{
						this.previewPic = ret
					})
				} else {
					this.$message.error(response.msg)
				}
			},
			//媒体资源上传之前时的钩子
			beforeMediaUpload(file) {
				console.log(file)
				var videoType = ['video/mp4']
				var picType = ['image/jpeg', 'image/png', 'image/jpg']
				const isPic = picType.join(',').indexOf(file.type) !== -1
				const isVideo = videoType.join(',').indexOf(file.type) !== -1
				let isBig = false;
				if (isPic) {
					this.dataForm.mediaType = 1
					isBig = file.size / 1024 / 1024 < 2
					if (!isBig) {
						this.$message.error('上传图片大小不能超过 2MB!')
					}
				} else if (isVideo) {
					this.dataForm.mediaType = 2
					isBig = file.size / 1024 / 1024 < 15
					if (!isBig) {
						this.$message.error('上传图片大小不能超过 15MB!')
					}
				} else {
					this.$message.error('不支持此格式的媒体类型!')
				}
				return (isPic || isVideo) && isBig
			},
			//查看媒体资源,使用时需要修改PhotoViewer源码文件中的zIndex
			handleView(imgUrl) {
				if (!imgUrl) {
					return ''
				}
				var reg = /(.*)\.(jpg|jpeg|png)$/;
				if (reg.test(imgUrl)) {
					var items = [{
						src: imgUrl
					}];
					var options = {
						index: 0
					};
					new PhotoViewer(items, options);
				}else{
					this.zvideoVisible=true;
					this.preVideoUrl=imgUrl;
				}
			},
			//删除媒体资源按钮点击事件
			deleteBtn(param) {
				var url = this.dataForm[param]
				if (url) {
					this.oldImg.push(url)
					this.dataForm[param] = ''
				}
			},
			// 删除图片数组
			deletePics(deleteImg) {
				for (var i = 0; i < deleteImg.length; i++) {
					this.deletePic(deleteImg[i])
				}
			},
			//删除媒体资源
			deletePic(url) {
				this.$http({
					url: this.$http.adornUrl('/sys/oss/deleteByUrl'),
					method: 'post',
					params: this.$http.adornParams({
						'url': url
					})
				})
			},
			//取消操作
			cancel() {
				this.deletePics(this.newImg)
				this.$emit('closeDialog')
				this.visible = false
			}
		}
	}
</script>
<style lang="scss">
	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		width: 100px;
		height: 100px;
		line-height: 100px;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		text-align: center;
	}

	.pic-url {
		width: 100%;
		height: 100%;
		display: block;
	}

	.upload-image-cover {
		width: 100%;
		height: 100%;
		position: relative;
	}

	.upload-list-cover {
		position: absolute;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
		background: rgba(0, 0, 0, .6);
		color: #ffffff;
		display: flex;
		display: -webkit-flex;
		justify-content: space-around;
		align-items: center;
		font-size: 20px;
	}

	.z-media {
		margin-top: 30px;
	}
</style>
